package com.gzhryc.net_marketing.cloud.micro.api.controllers.v1;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;

import com.gzhryc.common.NumberTools;
import com.gzhryc.common.StringTools;
import com.gzhryc.common.config.PropertyTools;
import com.gzhryc.common.event.DelayHandleService;
import com.gzhryc.common.exceptions.LogicException;
import com.gzhryc.common.json.JsonTools;
import com.gzhryc.common.logging.Logger;
import com.gzhryc.net_marketing.cloud.business.PayConfig;
import com.gzhryc.net_marketing.cloud.business.dao.db.PayGoodsOrder;
import com.gzhryc.net_marketing.cloud.business.dao.enums.PayGoodsOrderLogEnum;
import com.gzhryc.net_marketing.cloud.business.event.PayOrderLogEvent;
import com.gzhryc.net_marketing.cloud.business.services.PayGoodsOrderService;
import com.gzhryc.net_marketing.cloud.business.services.models.PayGoodsOrderLogItem;
import com.gzhryc.net_marketing.cloud.goods.dao.db.Goods;
import com.gzhryc.net_marketing.cloud.goods.dao.db.GoodsSpace;
import com.gzhryc.net_marketing.cloud.goods.dao.enums.GoodsEnum;
import com.gzhryc.net_marketing.cloud.goods.services.GoodsService;
import com.gzhryc.net_marketing.cloud.goods.services.GoodsSpaceService;
import com.gzhryc.net_marketing.cloud.goods.services.dto.GoodsSearch;
import com.gzhryc.net_marketing.cloud.logistics.LogisticsCostUtils;
import com.gzhryc.net_marketing.cloud.micro.api.ClientAPICodeConstants;
import com.gzhryc.net_marketing.cloud.micro.api.MicroConstants;
import com.gzhryc.net_marketing.cloud.micro.api.dto.v1.FindGoodsRequest;
import com.gzhryc.net_marketing.cloud.micro.api.dto.v1.FindGoodsResponse;
import com.gzhryc.net_marketing.cloud.micro.api.dto.v1.GetGoodsRequest;
import com.gzhryc.net_marketing.cloud.micro.api.dto.v1.GetGoodsResponse;
import com.gzhryc.net_marketing.cloud.micro.api.dto.v1.GoodsPayCheckRequest;
import com.gzhryc.net_marketing.cloud.micro.api.dto.v1.GoodsPayCheckResponse;
import com.gzhryc.net_marketing.cloud.micro.api.dto.v1.GoodsPayRequest;
import com.gzhryc.net_marketing.cloud.micro.api.dto.v1.GoodsPayResponse;
import com.gzhryc.net_marketing.core.enums.EGoodsClassify;
import com.gzhryc.pay.adaptation.weixin.DefaultWXPayConfig;
import com.gzhryc.pay.adaptation.weixin.WXPayNormalPayService;
import com.gzhryc.pay.adaptation.weixin.msg.normal.WXPayNormalPayResponse;
import com.gzhryc.servlet.WebUtils;
import com.gzhryc.servlet.annotation.Route;
import com.gzhryc.shared_device.base.ILogisticsCostConfig;
import com.gzhryc.shared_device.base.enums.EOperatorType;
import com.gzhryc.shared_device.base.enums.EPayType;
import com.gzhryc.shared_device.base.models.OperateInfo;
import com.gzhryc.shared_device.common.payment.dao.db.WXPayOrder;
import com.gzhryc.shared_device.common.payment.dao.enums.WXPayConfigEnum.AppType;
import com.gzhryc.shared_device.common.payment.services.WXPayOrderService;
import com.gzhryc.shared_device.oem.code.BaseConstants;
import com.gzhryc.shared_device.oem.code.ConfigUtils;
import com.gzhryc.shared_device.oem.code.PayServiceFactory;
import com.gzhryc.shared_device.oem.code.business.EBusinessType;
import com.gzhryc.shared_device.oem.code.config.BusinessConfig;
import com.gzhryc.shared_device.oem.code.config.services.LogisticsCostConfigService;
import com.gzhryc.shared_device.oem.code.member.LoginMember;
import com.gzhryc.shared_device.oem.code.member.dao.db.Member;
import com.gzhryc.shared_device.oem.code.member.dao.db.MemberAddress;
import com.gzhryc.shared_device.oem.code.member.dao.db.MemberWallet;
import com.gzhryc.shared_device.oem.code.member.dao.enums.MemberEnum;
import com.gzhryc.shared_device.oem.code.member.services.MemberAddressService;
import com.gzhryc.shared_device.oem.code.member.services.MemberService;
import com.gzhryc.shared_device.oem.code.member.services.MemberWalletService;

public class GoodsController {
	
	static Logger log = Logger.getLogger(GoodsController.class);

	@Route(value = { "/goods/list.data" })
	public FindGoodsResponse findGoods(HttpServletRequest request) {
		FindGoodsResponse apiResp = new FindGoodsResponse(ClientAPICodeConstants.NULL_DATA,"暂无数据");
		FindGoodsRequest apiReq = WebUtils.getJsonRequest(request, FindGoodsRequest.class);
		log.info("获取商品列表请求：{{0:json}}", apiReq);
		if (apiReq != null) {
			GoodsSearch search = new GoodsSearch();
			search.setState(GoodsEnum.State.PutOnTheShelf.index());

			List<Goods> goodsList = GoodsService.self().findBySearch(search, apiReq.getBody().getPageNo(),
					apiReq.getBody().getPageLimit());
			if (goodsList != null && goodsList.size() > 0) {
				apiResp.setCode(ClientAPICodeConstants.SUCCESS,null);
				String resDomain = PropertyTools.get().getString("marketResDomain");
				for (Goods goods : goodsList) {
					FindGoodsResponse.Item item = new FindGoodsResponse.Item();
					item.setGoodsId(goods.getId());
					if(StringUtils.isNotBlank(goods.getThumbnailImg()) && !goods.getThumbnailImg().startsWith("http")){
						item.setThumbnailImg(resDomain + goods.getThumbnailImg());
					}else {
						item.setThumbnailImg(goods.getThumbnailImg());
					}
					item.setGoodsName(goods.getName());
					item.setGoodsTypeNames(goods.getTypeNames());
					item.setGoodsLabels(goods.getLabels());
					item.setPayMoney(goods.getPayMoneyStr());
					item.setTeamPayMoney(goods.getTeamPayMoneyStr());
					item.setTeamMemberTotal(goods.getTeamCount());
					if(goods.getGainCount() == 0){
						item.setGainCount(30);		//默认30个
					}else {
						item.setGainCount(goods.getGainCount());
					}
					//检查是否启用积分
					BusinessConfig config = ConfigUtils.getBusinessConfig();
					if(config.getCanVirtualMoney()) {
						item.setCanVirtualMoney(goods.getCanVirtualMoney());
						if(goods.getCanVirtualMoney()) {
							//1毛 = 1000分
							Integer virtualMoney = goods.getPayMoney() * 1000;
							item.setVirtualMoney(virtualMoney);
						}
					}else {
						item.setCanVirtualMoney(false);
					}
					apiResp.getBody().getItems().add(item);
				}
			}
		}
		return apiResp;
	}

	@Route(value = { "/goods/info.data" })
	public GetGoodsResponse getGoods(HttpServletRequest request) {
		GetGoodsResponse apiResp = new GetGoodsResponse(ClientAPICodeConstants.EXECUTE_ERROR, "获取失败，请稍后再试");
		GetGoodsRequest apiReq = WebUtils.getJsonRequest(request, GetGoodsRequest.class);
		if (apiReq != null && apiReq.getBody().getGoodsId() != null) {
			Goods goods = GoodsService.self().getById(apiReq.getBody().getGoodsId());
			if (goods != null) {
				apiResp.setCode(ClientAPICodeConstants.SUCCESS, null);
				apiResp.getBody().setGoodsId(goods.getId());
				apiResp.getBody().setState(goods.getState());

				String resDomain = PropertyTools.get().getString("marketResDomain");
				if(StringUtils.isNotBlank(goods.getImgs())) {
					apiResp.getBody().setGoodsImgs(new ArrayList<>());
					String[] temp = goods.getImgs().split("\\|");
					for(int i =0;i<temp.length;i++){
						if(!temp[i].startsWith("http")){
							apiResp.getBody().getGoodsImgs().add(resDomain + temp[i]);
						}else{
							apiResp.getBody().getGoodsImgs().add(temp[i]);
						}
					}
				}
				if(StringUtils.isNotBlank(goods.getThumbnailImg()) && !goods.getThumbnailImg().startsWith("http")){
					apiResp.getBody().setThumbnailImg(resDomain + goods.getThumbnailImg());
				}else {
					apiResp.getBody().setThumbnailImg(goods.getThumbnailImg());
				}
				apiResp.getBody().setGoodsName(goods.getName());
				apiResp.getBody().setGoodsTypeNames(goods.getTypeNames());
				apiResp.getBody().setPayMoney(goods.getPayMoneyStr());
				apiResp.getBody().setTeamPayMoney(goods.getTeamPayMoneyStr());
				apiResp.getBody().setTeamMemberTotal(goods.getTeamCount());
				if(goods.getGainCount() == 0){
					apiResp.getBody().setGainCount(30);		//默认30个
				}else {
					apiResp.getBody().setGainCount(goods.getGainCount());
				}
				apiResp.getBody().setClassify(goods.getClassify());

				if(StringUtils.isNotBlank(goods.getDetailImgs())){
					apiResp.getBody().setDetailImgs(new ArrayList<>());
					String[] temp = goods.getDetailImgs().split("\\|");
					for(int i =0;i<temp.length;i++) {
						if(!temp[i].startsWith("http")){
							apiResp.getBody().getDetailImgs().add(resDomain + temp[i]);
						}else{
							apiResp.getBody().getDetailImgs().add(temp[i]);
						}
					}
				}
				//检查是否启用积分
				BusinessConfig config = ConfigUtils.getBusinessConfig();
				if(config.getCanVirtualMoney()) {
					apiResp.getBody().setCanVirtualMoney(goods.getCanVirtualMoney());
				}

				apiResp.getBody().setSupplierId(goods.getSupplierId());		//用于计算物流费，先传给前端，然后前端传给后端计算，减少服务器压力

				List<GoodsSpace> goodsSpaceList = GoodsSpaceService.self().findPutByGoodsId(goods.getId());
				if(goodsSpaceList != null && goodsSpaceList.size() > 0){
					apiResp.getBody().setSpecifications(new ArrayList<>());
					for(GoodsSpace goodsSpace : goodsSpaceList){
						GetGoodsResponse.Specification specification = new GetGoodsResponse.Specification();
						specification.setId(goodsSpace.getId());
						if(StringUtils.isNotBlank(goodsSpace.getThumbnailImg()) && !goodsSpace.getThumbnailImg().startsWith("http")){
							specification.setThumbnailImg(resDomain + goodsSpace.getThumbnailImg());
						}else {
							specification.setThumbnailImg(goodsSpace.getThumbnailImg());
						}
						specification.setName(goodsSpace.getName());
						specification.setStockNum(goodsSpace.getStockNum());
						apiResp.getBody().getSpecifications().add(specification);
					}
				}
			}
		}
		return apiResp;
	}

	@Route(value = { "/goods/pay/check.do" })
	public GoodsPayCheckResponse payScope(HttpServletRequest request){
		GoodsPayCheckResponse apiResp = new GoodsPayCheckResponse(ClientAPICodeConstants.NULL_DATA);
		GoodsPayCheckRequest apiReq = WebUtils.getJsonRequest(request,GoodsPayCheckRequest.class);
		LoginMember loginMember = WebUtils.getAttribute(request, MicroConstants.ATTR_LOGIN_MEMBER, LoginMember.class);
		if(apiReq != null && apiReq.getBody().getGoodsId() != null && apiReq.getBody().getGoodsNum() != null 
				&& apiReq.getBody().getBuyType() != null && loginMember != null){
			Goods goods = GoodsService.self().getById(apiReq.getBody().getGoodsId());
			if(goods == null){
				apiResp.setCode(ClientAPICodeConstants.EXECUTE_ERROR,"未找到商品信息");
				return apiResp;
			}

			if(GoodsEnum.State.OffTheShelf.index().equals(goods.getState())){
				apiResp.setCode(ClientAPICodeConstants.EXECUTE_ERROR, "商品已下架");
				return apiResp;
			}else if(GoodsEnum.State.NoInventory.index().equals(goods.getState())){
				apiResp.setCode(ClientAPICodeConstants.EXECUTE_ERROR, "商品暂无库存");
				return apiResp;
			}

			Integer money = 0;
			if(apiReq.getBody().getBuyType().equals(1)){
				money = goods.getPayMoney() * apiReq.getBody().getGoodsNum();
				apiResp.getBody().setGoodsMoney(NumberTools.changeMoney(goods.getPayMoney()));
			}else if(apiReq.getBody().getBuyType().equals(2)){
				money = goods.getTeamPayMoney() * apiReq.getBody().getGoodsNum();
				apiResp.getBody().setGoodsMoney(NumberTools.changeMoney(goods.getTeamPayMoney()));
			}else {
				apiResp.setCode(ClientAPICodeConstants.EXECUTE_ERROR,"未找到商品价格信息");
				return apiResp;
			}

			Integer couponMoney = 0;
			Integer logisticsMoney = 0;
			try {
				//只有实体商品处理物流
				if(EGoodsClassify.Entity.index().equals(goods.getClassify())) {
					MemberAddress memberAddress = null;
					if(apiReq.getBody().getAddressId() != null && apiReq.getBody().getAddressId() != 0L) {
						memberAddress = MemberAddressService.self(BaseConstants.JDBC_KEY).getByKeys(loginMember.getId(),apiReq.getBody().getAddressId());
					}
					if(memberAddress == null){
						memberAddress = MemberAddressService.self(BaseConstants.JDBC_KEY).getDefByMemberId(loginMember.getId());
					}
					String province = null;
					if(memberAddress != null && StringUtils.isNotBlank(memberAddress.getProvince())){
						province = memberAddress.getProvince();
					}
	
					ILogisticsCostConfig logisticsCostConfig = null;
					if(goods.getSupplierId() != null){
						//获取供货商物流费用
						logisticsCostConfig = LogisticsCostUtils.getUsableConfig(goods.getSupplierId()
								,apiReq.getBody().getLogisticsCompanyId(),province);
					}else {
						//使用系统物流费用
						logisticsCostConfig = LogisticsCostConfigService.self(BaseConstants.JDBC_KEY)
								.getUsableConfig(apiReq.getBody().getLogisticsCompanyId(), province);
					}
	
					if (logisticsCostConfig == null) {
						apiResp.setCode(ClientAPICodeConstants.EXECUTE_ERROR,"未找到物流价格配置");
						return apiResp;
					} else {
						boolean free = false;
						if(goods.getSupplierId() != null){
							//使用批发价
							Integer wholesaleMoney = goods.getWholesaleMoney() * apiReq.getBody().getGoodsNum();
							if (LogisticsCostUtils.isFree(logisticsCostConfig,wholesaleMoney)) {
								free = true;
							}
						}else if(LogisticsCostUtils.isFree(logisticsCostConfig,money)){
							free = true;
						}
	
						GoodsPayCheckResponse.LogisticsInfo logisticsInfo = new GoodsPayCheckResponse.LogisticsInfo();
						if (free) {
							log.info("客单价触发免邮费，客单价：{{0}}，阀值：{{1}}", money, logisticsCostConfig.getFreeMinMoney());
	
							logisticsInfo.setCompanyId(logisticsCostConfig.getCompanyId());
							logisticsInfo.setName(logisticsCostConfig.getCompanyName());
							logisticsInfo.setMoney("包邮");
						} else {
							logisticsMoney = logisticsCostConfig.getMoney();
							money = money + logisticsMoney;
	
							logisticsInfo.setCompanyId(logisticsCostConfig.getCompanyId());
							logisticsInfo.setName(logisticsCostConfig.getCompanyName());
							logisticsInfo.setMoney(NumberTools.getMoneyStr(logisticsCostConfig.getMoney()) + "元");
						}
						apiResp.getBody().setLogistics(logisticsInfo);
					}
	
					if(memberAddress != null){
						GoodsPayCheckResponse.DefAddress defAddress = new GoodsPayCheckResponse.DefAddress();
						defAddress.setId(memberAddress.getId());
						defAddress.setReceiveName(memberAddress.getReceiveName());
						defAddress.setReceivePhone(memberAddress.getReceivePhone());
						defAddress.setAddress(memberAddress.getFullAddress());
						apiResp.getBody().setAddress(defAddress);
					}
				}
			}catch (LogicException e){
				apiResp.setCode(ClientAPICodeConstants.EXECUTE_ERROR,e.getMessage());
				return apiResp;
			}

			apiResp.getBody().setMoney(NumberTools.changeMoney(money));		//总价格，包括物流费

			if(StringUtils.isNotBlank(apiReq.getBody().getCouponId())){
				/*CouponMemberRecord couponMemberRecord = CouponMemberRecordService.self().getUnableByIdAndMemberId(apiReq.getBody().getCouponId(),member.getId());
				if(couponMemberRecord == null){
					apiResp.setCode(ClientAPICodeConstants.EXECUTE_ERROR,"优惠券已失效，请重新选择");
					return apiResp;
				}else{
					if(couponMemberRecord.getMinimumCharge() > 0 && couponMemberRecord.getMinimumCharge() < money){
						apiResp.setCode(ClientAPICodeConstants.EXECUTE_ERROR,"该优惠券未到达最低消费标准");
						return apiResp;
					}
					if(CouponActivityEnum.CouponType.Discount.index().equals(couponMemberRecord.getCouponType())){
						couponMoney = NumberTools.discount(money,couponMemberRecord.getCouponDiscount());
					}else{
						couponMoney = couponMemberRecord.getCouponMoney();
					}
				}*/
			}

			MemberWallet wallet = MemberWalletService.self(BaseConstants.JDBC_KEY).getByMemberId(loginMember.getId());
			if(wallet != null){
				//直接购买可以使用组合支付
				Long virtualMoney = 0L;
				if(apiReq.getBody().getVirtualMoney() > 999) {
					virtualMoney = (apiReq.getBody().getVirtualMoney() / 1000) * 1000;
				}
				Long maxVirtualMoney = 0L;
				Integer walletMoney = NumberTools.changeMoney(apiReq.getBody().getWalletMoney());
				Integer payMoney = 0;

				Integer maxWalletMoney = NumberTools.changeMoney(NumberTools.changeMoneyLi(wallet.getMoney()));
				if(wallet.getVirtualMoney() > 999) {
					maxVirtualMoney = (wallet.getVirtualMoney() / 1000) * 1000;
				}

				//对传值进行最大值检查
				if(virtualMoney > maxVirtualMoney){
					virtualMoney = wallet.getVirtualMoney();
				}
				
				if(walletMoney > maxWalletMoney){
					walletMoney = maxWalletMoney;
				}
				
				//转换积分 1000 = 1毛
				Integer replaceMoney = 0;
				if(virtualMoney > 1000) {
					replaceMoney = virtualMoney.intValue() / 1000;
					
					if(replaceMoney > money) {
						virtualMoney = money * 1000L;
						replaceMoney = money;
					}
				}
				
				//计算优惠金额
				couponMoney = couponMoney + replaceMoney;

				Integer tempMoney = walletMoney + couponMoney;
				if(tempMoney < money){
					payMoney = money - couponMoney - walletMoney ;
				}else{
					payMoney = 0; //无需支付
					if(walletMoney > 0) {
						walletMoney = money - couponMoney;
						if(walletMoney < 0) {
							walletMoney = 0;
						}else if(walletMoney > maxWalletMoney){
							walletMoney = maxWalletMoney;
							payMoney = money - couponMoney - walletMoney;
							if(payMoney < 0) {	//避免负数出现
								payMoney = 0;
							}
						}
					}
				}
				apiResp.setCode(ClientAPICodeConstants.SUCCESS);
				apiResp.getBody().setVirtualMoney(virtualMoney);
				apiResp.getBody().setMaxVirtualMoney(maxVirtualMoney);
				apiResp.getBody().setWalletMoney(NumberTools.changeMoney(walletMoney));
				apiResp.getBody().setMaxWalletMoney(NumberTools.changeMoney(maxWalletMoney));
				apiResp.getBody().setPayMoney(NumberTools.changeMoney(payMoney));
				apiResp.getBody().setCouponMoney(NumberTools.changeMoney(couponMoney));
			}else{
				log.info("未找到会员钱包，会员ID：{{0}}", loginMember.getId());
				
				apiResp.setCode(ClientAPICodeConstants.SUCCESS);
				apiResp.getBody().setPayMoney(NumberTools.changeMoney(money));
			}
		}
		return apiResp;
	}
	
	/**
	 * 直接购买商品
	 * @param request
	 * @return
	 */
	@Route(value = { "/goods/pay.do" })
	public GoodsPayResponse payGoods(HttpServletRequest request) {
		GoodsPayResponse apiResp = new GoodsPayResponse(ClientAPICodeConstants.EXECUTE_ERROR, "购买失败，请稍后再试！");
		GoodsPayRequest apiReq = WebUtils.getJsonRequest(request, GoodsPayRequest.class);
		if (apiReq != null) {
			log.info("直接购买商品请求：{{0:json}}", apiReq);
			LoginMember loginMember = WebUtils.getAttribute(request, MicroConstants.ATTR_LOGIN_MEMBER, LoginMember.class);
			PayGoodsOrder goodsPayOrder = null;
			
			OperateInfo operateInfo = new OperateInfo(MicroConstants.PROGRAM_TYPE, MicroConstants.PROGRAM_TYPE_NAME);
            operateInfo.setOperator(EOperatorType.Member.index(), loginMember.getFullName());
            operateInfo.setOperateNote("购买商品");
			
			if (StringTools.isNotBlank(apiReq.getBody().getTradeNo())) {
				goodsPayOrder = PayGoodsOrderService.self().getByTradeNo(apiReq.getBody().getTradeNo(), loginMember.getId());
				
				//二次支付
				PayConfig payConfig = new PayConfig();
				payConfig.setProjectId(goodsPayOrder.getProjectId());
				payConfig.setPayType(apiReq.getBody().getPayType());
				payConfig.setAppId(apiReq.getBody().getAppId());
				
				try {
					if (EPayType.WXPay.index().equals(payConfig.getPayType())) {
						if (!MemberEnum.Type.WxUser.index().equals(loginMember.getType())) {
							throw new LogicException("非微信用户");
						}
						DefaultWXPayConfig wxPayConfig = PayServiceFactory.self().getWXPayConfig(payConfig.getAppId(),EBusinessType.MARKET.index());
						payConfig.setAppType(AppType.wxxcx.index());
						payConfig.setPayerId(loginMember.getOpenId());
						payConfig.setBusinessAccount(wxPayConfig.getMchId());
						payConfig.setNotifyUrl(wxPayConfig.getPayNotifyUrl());
					} else {
						throw new LogicException("未知支付类型");
					}
					
					if (PayGoodsOrderService.self().againComposePayGoods(goodsPayOrder, payConfig, operateInfo)) {
						goodsPayOrder = PayGoodsOrderService.self().getByTradeNo(goodsPayOrder.getTradeNo());
						log.info("直接购买二次支付，订单号 = {{0}}，会员ID = {{1}}", goodsPayOrder.getTradeNo(), loginMember.getId());
						
						if(goodsPayOrder.getPayMoney()  > 0) {
							if(EPayType.WXPay.index().equals(payConfig.getPayType())) {
								WXPayOrder payOrder = WXPayOrderService.self(BaseConstants.JDBC_KEY,goodsPayOrder.getCreateDate())
										.getLastByBusinessTradeNo(goodsPayOrder.getTradeNo());
				                if(payOrder == null){
				                    throw new LogicException("未获取第三方支付订单");
				                }
				                
				                WXPayNormalPayService payService = PayServiceFactory.self().getWXPayNormalPayService(payOrder.getAppId(),EBusinessType.MARKET.index());
					            if (payService != null) {
					            	if(StringTools.isNotBlank(payOrder.getExternalPayContent())) {
					                	WXPayNormalPayResponse externalResult = JsonTools.fromJson(payOrder.getExternalPayContent(), WXPayNormalPayResponse.class);
					                	String prepayId = externalResult.getPrepay_id();
					                	String payInfo = payService.buildXCXData(prepayId);
				                    	
				                    	log.info("微信支付返回：" + payInfo);
										apiResp.setCode(ClientAPICodeConstants.SUCCESS, null);
										apiResp.getBody().setTradeNo(goodsPayOrder.getTradeNo());
										apiResp.getBody().setPayType(apiReq.getBody().getPayType());
										apiResp.getBody().setPayInfo(payInfo);
						            }else {
					                    WXPayNormalPayResponse externalResult = payService.applyPayOrder(payOrder);
					                    if(externalResult != null){
					                    	if(StringTools.isNotBlank(externalResult.getCode()) && "PARAM_ERROR".equals(externalResult.getCode())) {
					                    		if(StringTools.isNotBlank(externalResult.getMessage())) {
					                    			apiResp.setMsg(externalResult.getMessage());
					                    		}else {
					                    			apiResp.setMsg("创建微信支付订单失败");
					                    		}
					                    	}else {
						                    	String prepayId = externalResult.getPrepay_id();
						                    	WXPayOrderService.self(BaseConstants.JDBC_KEY,payOrder.getCreateDate()).updateExternalContent(payOrder.getTradeNo()
						                    			, JsonTools.toJson(externalResult), new Date());
						                    	
						                    	String payInfo = payService.buildXCXData(prepayId);
						                    	
						                    	log.info("微信支付返回：" + payInfo);
												apiResp.setCode(ClientAPICodeConstants.SUCCESS, null);
												apiResp.getBody().setTradeNo(goodsPayOrder.getTradeNo());
												apiResp.getBody().setPayType(apiReq.getBody().getPayType());
												apiResp.getBody().setPayInfo(payInfo);
					                    	}
					                    }
						            }
				                }else{
				                    throw new LogicException("未获取支付服务");
				                }
							}
						}
					} else {
						throw new LogicException("重新支付失败，请联系客服人员");
					}
				}catch (LogicException e) {
					apiResp.setMsg(e.getMessage());
					//记录问题
					PayGoodsOrderLogItem logsItem = new PayGoodsOrderLogItem();
					logsItem.setContent("会员再次支付");
					logsItem.setProgramType(MicroConstants.PROGRAM_TYPE);
					logsItem.setOperatorType(EOperatorType.Member.index());
					logsItem.setOperator(loginMember.getNickname() + "(" + loginMember.getId() + ")");
					logsItem.setState(PayGoodsOrderLogEnum.ItemState.Error.index());
					logsItem.setErrorMsg(e.getMessage());
					logsItem.setCreateDate(new Date());
					PayOrderLogEvent event = new PayOrderLogEvent(goodsPayOrder.getTradeNo(), goodsPayOrder.getCreateDate(), logsItem);
					DelayHandleService.get().addEvent(event);
				}
			} else {
				if(apiReq.getBody().getGoodsId() == null || apiReq.getBody().getGoodsNum() == null) {
					apiResp.setMsg("商品参数错误");
					return apiResp;
				}
				
				if (apiReq.getBody().getPayMoney() > 0) {
					if (StringUtils.isBlank(apiReq.getBody().getAppId())
							|| apiReq.getBody().getPayType() == null) {
						apiResp.setMsg("未知的支付应用");
						return apiResp;
					}
				}
				
				PayGoodsOrder temp = PayGoodsOrderService.self().getWaitingByGoodsIdAndMemberId(apiReq.getBody().getGoodsId(), loginMember.getId());
				if (temp != null) {
					apiResp.setCode(ClientAPICodeConstants.PAY_WAIT, "该商品有未支付订单，请优先使用");
					apiResp.getBody().setTradeNo(temp.getTradeNo());
					return apiResp;
				}
				
				/*CouponMemberRecord couponMemberRecord = null;
				if (StringUtils.isNotBlank(apiReq.getBody().getCouponId())) {
					couponMemberRecord = CouponMemberRecordService.self().getUnableByIdAndMemberId(apiReq.getBody().getCouponId(), member.getId());
					if (couponMemberRecord == null) {
						apiResp.setMsg("优惠券已失效，请重新选择");
						return apiResp;
					}
				}*/
				
				try {
					Member member = MemberService.self(BaseConstants.JDBC_KEY).getById(loginMember.getId());
					if(member == null) {
						throw new LogicException("未找到会员信息");
					}
					
					Goods goods = GoodsService.self().getById(apiReq.getBody().getGoodsId());
					if (goods == null) {
						throw new LogicException("商品不存在");
					}
					
					if (GoodsEnum.State.OffTheShelf.index().equals(goods.getState())) {
						throw new LogicException("商品已下架");
					} else if (GoodsEnum.State.NoInventory.index().equals(goods.getState())) {
						throw new LogicException("商品暂无库存");
					}
					
					GoodsSpace goodsSpace = null;
					if (apiReq.getBody().getSpecificationId()!= null) {
						goodsSpace = GoodsSpaceService.self().getByKeys(goods.getId(), apiReq.getBody().getSpecificationId());
						if (goodsSpace == null) {
							throw new LogicException("商品的规格不存在");
						}
					}
					
					MemberAddress mailAddress = null;
					if(EGoodsClassify.Entity.index().equals(goods.getClassify())) {
						if (apiReq.getBody().getAddressId() == null) {
							apiResp.setMsg("请选择收货地址");
							return apiResp;
						}
						
						mailAddress = MemberAddressService.self(BaseConstants.JDBC_KEY).getByKeys(loginMember.getId(),apiReq.getBody().getAddressId());
						if (mailAddress == null) {
							apiResp.setMsg("收货地址不存在，请重新选择");
							return apiResp;
						}
					}
					
					
					PayConfig payConfig = new PayConfig();
					payConfig.setProjectId(goods.getProjectId());
					payConfig.setPayType(apiReq.getBody().getPayType());
					payConfig.setAppId(apiReq.getBody().getAppId());
					payConfig.setNote(apiReq.getBody().getNote());
					payConfig.setMailAddress(mailAddress);
					payConfig.setLogisticsCompanyId(apiReq.getBody().getLogisticsCompanyId());
					payConfig.setPayMoney(NumberTools.changeMoney(apiReq.getBody().getPayMoney()));
					payConfig.setVirtualMoney(apiReq.getBody().getVirtualMoney());					//积分
					payConfig.setWalletMoney(NumberTools.changeMoney(apiReq.getBody().getWalletMoney()));
					
					//检查组合支付金额
					if (payConfig.getWalletMoney() > 0) {
						Long money = NumberTools.changeMoneyLi(NumberTools.changeMoney(payConfig.getWalletMoney()));
						if (!MemberWalletService.self().hasMoney(loginMember.getId(), money)) {
							throw new LogicException("钱包余额不足");
						}
					}
					if (payConfig.getVirtualMoney() > 0) {
						if (!MemberWalletService.self(BaseConstants.JDBC_KEY).hasVMoney(loginMember.getId(), payConfig.getVirtualMoney())) {
							throw new LogicException("积分不足");
						}
					}

					if (apiReq.getBody().getPayMoney() > 0) {
						payConfig.setClientIP(WebUtils.getClientIP(request));
						
						if (EPayType.WXPay.index().equals(payConfig.getPayType())) {
							if (!MemberEnum.Type.WxUser.index().equals(loginMember.getType())) {
								throw new LogicException("非微信用户");
							}
							DefaultWXPayConfig wxPayConfig = PayServiceFactory.self().getWXPayConfig(payConfig.getAppId(),EBusinessType.MARKET.index());
							payConfig.setAppType(AppType.wxxcx.index());
							payConfig.setPayerId(loginMember.getOpenId());
							payConfig.setBusinessAccount(wxPayConfig.getMchId());
							payConfig.setNotifyUrl(wxPayConfig.getPayNotifyUrl());
						} else {
							throw new LogicException("未知支付类型");
						}
					}

					goodsPayOrder = PayGoodsOrderService.self().composePayGoods(member, goods,goodsSpace, apiReq.getBody().getGoodsNum()
							, payConfig, operateInfo);
					
					if (goodsPayOrder != null) {
						log.info("直接购买支付，订单号 = {{0}}，会员ID = {{1}}", goodsPayOrder.getTradeNo(), loginMember.getId());
						
						if(goodsPayOrder.getPayMoney()  > 0) {
							if(EPayType.WXPay.index().equals(payConfig.getPayType()) || EPayType.WXComposePay.index().equals(payConfig.getPayType())) {
								WXPayOrder payOrder = WXPayOrderService.self(BaseConstants.JDBC_KEY,goodsPayOrder.getCreateDate())
										.getLastByBusinessTradeNo(goodsPayOrder.getTradeNo());
				                if(payOrder == null){
				                    throw new LogicException("未获取第三方支付订单");
				                }
				                
				                WXPayNormalPayService payService = PayServiceFactory.self().getWXPayNormalPayService(payOrder.getAppId(),EBusinessType.MARKET.index());
				                if (payService != null) {
				                    WXPayNormalPayResponse externalResult = payService.applyPayOrder(payOrder);
				                    if(externalResult != null){
				                    	String prepayId = externalResult.getPrepay_id();
				                    	WXPayOrderService.self(BaseConstants.JDBC_KEY,payOrder.getCreateDate()).updateExternalContent(payOrder.getTradeNo()
				                    			, JsonTools.toJson(externalResult), new Date());
				                    	
				                    	String payInfo = payService.buildXCXData(prepayId);
				                    	
				                    	log.info("微信支付返回：" + payInfo);
										apiResp.setCode(ClientAPICodeConstants.SUCCESS, null);
										apiResp.getBody().setTradeNo(goodsPayOrder.getTradeNo());
										apiResp.getBody().setPayType(apiReq.getBody().getPayType());
										apiResp.getBody().setPayInfo(payInfo);
										return apiResp;
				                    }
				                }else{
				                    throw new LogicException("未获取支付服务");
				                }
							}else {
								throw new LogicException("无效的支付类型");
							}
						}else {
							apiResp.setCode(ClientAPICodeConstants.PAY_SUCCESS, null);
							apiResp.getBody().setTradeNo(goodsPayOrder.getTradeNo());
						}
					}
				} catch (LogicException e) {
					apiResp.setMsg(e.getMessage());
				}
			}
		}
		return apiResp;
	}

}
